#!/usr/bin/env python
# -*- coding: utf-8 -*-
#coding=utf-8

import pexpect
import paramiko
import os
import sys
import getopt

def sftp(host, username, password, targetfile, sourcefile):
    try:
        sf = paramiko.Transport((host, 22))
        sf.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(sf)
        print(u"sourcefile: {0}".format(sourcefile))
        print(u"targetfile: {0}".format(targetfile))
        sftp.put(sourcefile, targetfile)
    except Exception as e:
        print(str(error))
    sf.close()

def scp2(ip, user, passwd, dst_path, filename):
    key = '.*assword.*'
    if os.path.isdir(filename):
        cmdline = 'scp -r {0} {1}@{2}:{3}'.format(filename, user, ip, dst_path)
    else:
        cmdline = 'scp {0} {1}@{2}:{3}'.format(filename, user, ip, dst_path)
    try:
        child = pexpect.spawn(cmdline)
        child.expect(key)
        child.sendline(passwd)
        child.expect(pexpect.EOF, timeout=600)
        child.logfile = sys.stdout
        child.close()
    except Exception as e:
        print(str(e))


def delete():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(Config.host, 22, Config.username, Config.password, timeout=5)
    for index, name in enumerate(Config.names):
        print(u"删除 {0} 开始!".format(name))
        ssh.exec_command("rm -rf /home/program/"+name+"/" + name + "-0.0.1-SNAPSHOT.jar")
        print(u"删除 {0} 成功!".format(name))
    ssh.close()


def upload():
    for index, name in enumerate(Config.names):
        print(u"上传 {0} 开始!".format(name))
        sftp(Config.host, Config.username, Config.password, "/home/miniprogram-cloud/"+name+"/" + name + "-0.0.1-SNAPSHOT.jar", Config.path + "/" + name + "/target/" + name + "-0.0.1-SNAPSHOT.jar")
        print(u"上传 {0} 完成!".format(name))


def kill():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(Config.host, 22, Config.username, Config.password, timeout=5)
    for index, name in enumerate(Config.names):
        print(u"查找 {0} pid!".format(name))
        pidin, pidout, piderr = ssh.exec_command("ps -ef | grep '" + name + "-0.0.1-SNAPSHOT.jar' | grep -w '" + name + "-0.0.1-SNAPSHOT.jar' | grep -v 'grep' | awk '{print $2}'")
        pid = pidout.readline().replace("\r", "").replace("\n", "")
        # pid = pid.encode("utf-8")
        print(u"终结进程 {0} 开始!".format(pid))
        ssh.exec_command("kill -9 {0}".format(pid))
        print(u"终结进程 {0} 完成!".format(pid))
    ssh.close()

def startup():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(Config.host, 22, Config.username, Config.password, timeout=5)
    for index, name in enumerate(Config.names):
        try:
            print(u"启动 {0} 开始!".format(name))

            str = u"/usr/java/jdk1.8.0_181-amd64/bin/java "
            if Config.product:
                str = u"/usr/bin/java "
            if Config.debug:
                str += u" -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + Config.debugPorts[index] + " "
            str += u" -jar /home/miniprogram-cloud/"+name+"/" + name + "-0.0.1-SNAPSHOT.jar "
            if Config.product:
                str += u" --spring.profiles.active=prod"
            str += u" &"
            print(str)
            finishin, finishout, finisherr = ssh.exec_command(str)
            print(u"启动 {0} 完成!".format(name))
            #err = finisherr.readlines()
            #for finishLine in err:
            #print finishLine
        except Exception as e:
            print(str(e))
    ssh.close()

class Config:

    host = "47.95.204.39"
    path = "/Users/doubletree/workspace/myserver/wish-cloud-parent"
    delete = True
    upload = True
    restart = True
    debug = False
    product = False

    #names = ["miniprogram-cloud-api","miniprogram-cloud-admin"]
    names = ["miniprogram-cloud-api"]
    #debugPorts = ["7500", "7600", "7700", "7800"]
    debugPorts = ["7700"]


    username = "root"
    password = "Ilove=shaolin"

    def __init__(self, host, path, delete, upload, restart, debug, product):
        self.host = host
        self.path = path
        self.delete = delete
        self.upload = upload
        self.restart = restart
        self.debug = debug
        self.product = product


if __name__ == '__main__':
    try:
        options, args = getopt.getopt(sys.argv[1:], "durh:p:ts", ["delete=", "upload=", "restart=", "host=", "path=", "debug=", "product="])
    except getopt.GetoptError as e:
        print(str(e))
        sys.exit()
    for name, value in options:
        if name in ("-h", "--host"):
            Config.host = value
        if name in ("-p", "--path"):
            Config.path = value
        if name in ("-d", "--delete"):
            Config.delete = False
        if name in ("-u", "--upload"):
            Config.upload = False
        if name in ("-r", "--restart"):
            Config.restart = False
        if name in ("-t", "--debug"):
            Config.debug = True
        if name in ("-s", "--product"):
            Config.product = True
    if Config.product:
        Config.host = "47.104.255.173"
        Config.password = "Ilove=shaolin"
    print("Host: {0}".format(Config.host))
    if Config.delete:
        delete()
    if Config.upload:
        upload()
    if Config.restart:
        kill()
        startup()
# python /Users/doubletree/workspace/myserver/wish-cloud-parent/doc/publish.py -p /Users/doubletree/workspace/myserver/wish-cloud-parent -t
# 公司电脑
# python D:/workspace/server/jmkj-parent/doc/deploy.py -p D:/workspace/server/jmkj-parent -t
# 家里电脑
# python D:/workspace/code/my/miniprogram-cloud-parent/doc/deploy.py -p D:/workspace/code/my/miniprogram-cloud-parent -t
# mac
# python /Users/doubletree/workspace/myserver/jmkj-parent/doc/deploy.py -p /Users/doubletree/workspace/myserver/jmkj-parent -t
# 线上环境
# python D:/workspace/code/my/jmkj-parent/doc/deploy.py -p D:/workspace/code/my/jmkj-parent -s